<template>
  <!-- 登录顶部 -->

  <div class="login">
    <van-nav-bar title="登录" />
    <!-- 验证 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        required
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请填写手机名' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '请填写正确的手机号'
          }
        ]"
      />
      <van-field
        v-model="code"
        type="code"
        name="code"
        label="验证码"
        required
        placeholder="请输入验证号"
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /\d{6}/, message: '请填写正确的验证码' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoading"
          :disabled="isLoading"
          loading-text="加载中"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { useLogin } from '../../api/login'
import { saveToken } from '../../until/token.js'
export default {
  name: 'login',
  data () {
    return {
      mobile: '18296748874',
      code: '246810',
      isLoading: false
    }
  },
  // created () {
  //   const token = saveToken()
  //   console.log('token:', token)
  // },
  methods: {
    onSubmit (values) {
      // values是一个对象{model:xxx,code:xxx}
      //   console.log('submit', values)
      this.isLoading = true

      useLogin(values)
        .then(res => {
          // 调用接口
          console.log('res:', res)
          saveToken(res.data.data)
          setTimeout(() => {
            this.$toast.success('登录成功') // 弹出不同提示
            this.isLoading = false
            // 判断对否有back
            const back = this.$route.query.back
            if (back) {
              return this.$router.push({ path: back })
            }
            // 没有back
            this.$router.push({ path: '/index' })
          })
        }, 500)
        .catch(errRes => {
          console.log('errRes:', errRes)
          this.$toast.fail('登录失败')
          this.isLoading = false
        })
    }
  }
}
</script>

<style>
.login .van-nav-bar {
  background-color: #3196fa;
}
.van-nav-bar .van-nav-bar__title {
  color: #fff;
}
</style>
